package com.imooc.security.order;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/orders")
@Slf4j
public class OrderController {

    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private OAuth2RestTemplate oAuth2RestTemplate;

    //创建订单
    @PostMapping
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public OrderInfo create(@RequestBody OrderInfo info,@AuthenticationPrincipal String username) {
        log.info("username  is {}",username);
        log.info("price  is {}",info.getProductId());
        PriceInfo price = oAuth2RestTemplate.getForObject("http://192.168.0.35:8082/prices/"+info.getProductId(),PriceInfo.class);
        log.info("price  is {}",price.getPrice());
        return info;
    }

    //获取信息
    @GetMapping("/{id}")
    public OrderInfo getInfo(@PathVariable Long id,@AuthenticationPrincipal(expression = "#this.username") String username) {
        OrderInfo info = new OrderInfo();
        info.setId(id);
        info.setProductId(id*5);
        log.info("orderId  is {}",id);
        log.info("username  is {}",username);
//        PriceInfo price = restTemplate.getForObject("http://192.168.0.35:8082/prices/"+info.getProductId(),PriceInfo.class);
//        log.info("price  is {}",price.getPrice());
        return info;
    }


}
